package com.clss.commandhelper.tools.janus.janusclientapi;

import org.json.JSONObject;

import java.math.BigInteger;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;
import okio.ByteString;

/**
 * 用OKhttp3的websocket完成功能
 * Created by liuv on 2017/6/29.
 */

class JanusWebsocketMessenger implements IJanusMessenger {
    private static final String TAG = "JanusWebsocketMessanger";

    private String url;
    private final IJanusMessageObserver handler;
    private final JanusMessengerType type = JanusMessengerType.websocket;
    private WebSocket mWebSocket = null;
    private OkHttpClient mClient = null;

    public JanusWebsocketMessenger(String uri, IJanusMessageObserver handler) {
        this.url = uri;
        this.handler = handler;
    }

    @Override
    public void connect() {
        mClient = new OkHttpClient.Builder()
                .readTimeout(30, TimeUnit.SECONDS)
                .build();
        Request request = new Request.Builder().url(url).addHeader("Sec-WebSocket-Protocol", "janus-protocol").build();
        mClient.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                mWebSocket = webSocket;
                handler.onOpen();
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                receivedMessage(text);
            }

            @Override
            public void onMessage(WebSocket webSocket, ByteString bytes) {
                super.onMessage(webSocket, bytes);
            }

            @Override
            public void onClosing(WebSocket webSocket, int code, String reason) {
                super.onClosing(webSocket, code, reason);
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                handler.onClose();
                mWebSocket = null;
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                handler.onError(new ExecutionException(t));
            }
        });

        mClient.dispatcher().executorService().shutdown();
    }

    @Override
    public void disconnect() {
        if (mWebSocket != null){
            mWebSocket.cancel();
        }
    }

    @Override
    public void sendMessage(String message) {
        mWebSocket.send(message);
    }

    @Override
    public void sendMessage(String message, BigInteger session_id) {
        mWebSocket.send(message);
    }

    @Override
    public void sendMessage(String message, BigInteger session_id, BigInteger handle_id) {
        mWebSocket.send(message);
    }

    @Override
    public void receivedMessage(String message) {
        try {
            JSONObject obj = new JSONObject(message);
            handler.receivedNewMessage(obj);
        } catch (Exception ex) {
            handler.onError(ex);
        }
    }

    @Override
    public JanusMessengerType getMessengerType() {
        return type;
    }
}
